import subprocess
import re


def get_network_interfaces_and_ipv4():
    # 创建一个字典来存储网卡名称和对应的 IPv4 地址信息
    nic_ipv4_map = {}

    # 使用 subprocess 调用 netsh interface ipv4 show address命令获取所有网卡的 IPv4 地址信息
    result = subprocess.run(['netsh', 'interface', 'ipv4', 'show', 'address'], capture_output=True, text=True)
    output = result.stdout

    # 使用正则表达式匹配网卡名称和 IPv4 地址信息
    # 注意：netsh 命令的输出格式可能会因 Windows 版本而异，这里提供的正则表达式可能需要调整
    nic_pattern = re.compile(r'接口 "(.*)" 的配置', re.MULTILINE)
    ipv4_dhcp = re.compile(r'(.*DHCP 已启用): (.*)', re.IGNORECASE)
    ipv4_address = re.compile(r'(.*IP 地址): (.*\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)', re.IGNORECASE)
    ipv4_mask = re.compile(r'(.*子网前缀): .*掩码 (\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)', re.IGNORECASE)
    ipv4_gateway = re.compile(r'(.*默认网关): (.*\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b)', re.IGNORECASE)

    current_nic_name = None
    for line in output.splitlines():
        nic_match = nic_pattern.match(line)
        if nic_match:
            current_nic_name = nic_match.group(1).strip()
            # 初始化字典中的网卡条目
            nic_ipv4_map[current_nic_name] = []
        elif current_nic_name and ipv4_dhcp.search(line):
            ipv4_match = ipv4_dhcp.search(line)
            name = ipv4_match.group(1)
            dhcp = ipv4_match.group(2).strip()
            # 存储 IPv4 名称及dhcp开关
            nic_ipv4_map[current_nic_name].append((name, dhcp))
        elif current_nic_name and ipv4_address.search(line):
            ipv4_match = ipv4_address.search(line)
            name = ipv4_match.group(1)
            address = ipv4_match.group(2).strip()
            # 存储 IPv4 名称及地址
            nic_ipv4_map[current_nic_name].append((name, address))
        elif current_nic_name and ipv4_mask.search(line):
            ipv4_match = ipv4_mask.search(line)
            name = ipv4_match.group(1)
            mask = ipv4_match.group(2).strip()
            # 存储 IPv4 名称及前缀
            nic_ipv4_map[current_nic_name].append((name, mask))
        elif current_nic_name and ipv4_gateway.search(line):
            ipv4_match = ipv4_gateway.search(line)
            name = ipv4_match.group(1)
            gateway = ipv4_match.group(2).strip()
            # 存储 IPv4 名称及网关
            nic_ipv4_map[current_nic_name].append((name, gateway))

    return nic_ipv4_map


if __name__ == "__main__":
    network_interfaces = get_network_interfaces_and_ipv4()
    for nic_name, ipv4_pattern in network_interfaces.items():
        exist = 0
        for name, pattern in ipv4_pattern:
            if exist == 0:
                print(f'{nic_name}')
                exist = 1
            print(f'{name} : {pattern}')